from pydantic import BaseModel, Field, ConfigDict
from datetime import datetime
from typing import Optional, Dict, Any
from schemas.base import ResponseModel
from schemas.user import UserBase
from schemas.drone import DroneBase
from schemas.task import TaskBase


class ExceptionLogBase(BaseModel):
    exception_type: str = Field(..., description="异常类型", pattern="^(system_error|device_failure|task_interruption)$")
    exception_level: str = Field(..., description="异常级别", pattern="^(critical|warning|info)$")
    title: str = Field(..., description="异常标题", max_length=200)
    description: Optional[str] = Field(None, description="异常详细描述")
    drone_id: Optional[int] = Field(None, description="关联无人机ID")
    task_id: Optional[int] = Field(None, description="关联任务ID")
    detection_log_id: Optional[int] = Field(None, description="关联检测日志ID")
    location: Optional[Dict[str, Any]] = Field(None, description="异常发生位置信息")
    responsible_user_id: Optional[int] = Field(None, description="责任人ID")
    status: str = Field(default="pending", description="处理状态", pattern="^(pending|resolved)$")
    resolution_description: Optional[str] = Field(None, description="解决描述")


class ExceptionLogCreate(ExceptionLogBase):
    pass


class ExceptionLogUpdate(BaseModel):
    responsible_user_id: Optional[int] = Field(None, description="责任人ID")
    status: Optional[str] = Field(None, description="处理状态", pattern="^(pending|resolved)$")
    resolution_description: Optional[str] = Field(None, description="解决描述")


class ExceptionLogInDB(ExceptionLogBase):
    model_config = ConfigDict(from_attributes=True)
    id: int
    created_at: datetime
    updated_at: datetime
    resolution_time: Optional[datetime] = None


class ExceptionLogResponse(ExceptionLogInDB):
    responsible_user: Optional[UserBase] = None
    drone: Optional[DroneBase] = None
    task: Optional[TaskBase] = None


class ExceptionLogListResponse(ResponseModel):
    data: list[ExceptionLogResponse]
    total: int